package com.atguigu.admin.controller;

import com.atguigu.admin.param.AdminUserParam;
import com.atguigu.admin.pojo.AdminUser;
import com.atguigu.admin.service.AdminUserService;
import com.atguigu.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;

@RestController
@RequestMapping("user")
public class AdminUserController {


    @Autowired
    private AdminUserService adminUserService;

    // 表单数据不要@RequestBody，而json格式才要@RequestBody
    @PostMapping("login")
    public R login( @Validated AdminUserParam adminUserParam, BindingResult result, HttpSession session){

        if(result.hasErrors()){
            return R.fail("参数错误，登录失败");
        }

        String verCode = adminUserParam.getVerCode();
        String captcha = (String) session.getAttribute("captcha");
        if(!verCode.equalsIgnoreCase(captcha)){
            return R.fail("验证码错误");
        }
        R r=adminUserService.login(adminUserParam);

        // 将用户信息存入session共享键（key=userInfo）
        AdminUser adminUser = (AdminUser) r.getData();
        session.setAttribute("userInfo",adminUser);
        return r;
    }

    @GetMapping("logout")
    public R logout(HttpSession session){
        session.invalidate();// 清空session
        return R.ok("退出登录成功");
    }

}
